package com.xiaoze.steampy.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoze.steampy.common.dto.LoginDto;
import com.xiaoze.steampy.common.dto.UpdateMessage;
import com.xiaoze.steampy.common.dto.UpdatePassDto;
import com.xiaoze.steampy.common.lang.Result;
import com.xiaoze.steampy.entity.Rechargerecord;
import com.xiaoze.steampy.entity.User;
import com.xiaoze.steampy.service.RechargerecordService;
import com.xiaoze.steampy.service.UserService;
import org.apache.shiro.authc.Account;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小泽
 * @since 2022-03-28
 */
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RechargerecordService rechargerecordService;

    /*
     * 修改密码
     * */

    @PostMapping(value = "/user/updatepass")
    public Result update(@Validated @RequestBody UpdatePassDto updatePassDto) {
        User user = userService.getById(Integer.parseInt(updatePassDto.getId()));
        if (!user.getPassword().equals(SecureUtil.md5(updatePassDto.getLastpass()))) {
            return Result.fail("旧密码错误，请重新修改！");
        }
        user.setPassword(SecureUtil.md5(updatePassDto.getPass()));
        boolean b = userService.saveOrUpdate(user);
        if (b) {
            return Result.succ("修改成功");
        }
        return Result.fail("修改失败，请检查网络原因");
    }
    /*
     * 修改个人信息
     * */

    @PostMapping("/user/updateMessage")
    public Result updateMessage(@Validated @RequestBody UpdateMessage updateMessage) {
        User user = userService.getById(updateMessage.getId());
        user.setSex(updateMessage.getSex());
        user.setArea(updateMessage.getArea());
        user.setIntroduction(updateMessage.getIntroduction());
        System.out.println(user);
            boolean flog = userService.saveOrUpdate(user);
            if(flog){
                return Result.succ("修改成功");
            }
            return Result.fail("修改失败");
        }


    /*
     * 修改个人头像
     * */

    @RequestMapping("/updateUserPic")
    public Result updatePic(@RequestParam("file") MultipartFile avatorFile,
                            @RequestParam("id") Integer id){

        Assert.notNull(avatorFile,"文件为空，上传错误");
        User user = userService.getById(id);
        Assert.notNull(user,"用户信息不存在，上传错误");

        //文件名 = 当前时间到毫秒+原来的文件名
        String filename = System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"img"
                +System.getProperty("file.separator")+"pic"+System.getProperty("file.separator");

        String deletefile = (System.getProperty("user.dir")+System.getProperty("file.separator"))
                .replaceAll("\\\\","/")
                +user.getPic().substring(1);

        File file = new File(deletefile);

        //如果文件路径不存在，新增该路径
        File file1= new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }

        //实际的文件地址
        File dest = new File(filePath + System.getProperty("file.separator") + filename);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/img/pic/"+filename;
        try {
            avatorFile.transferTo(dest);
            user.setPic(storeAvatorPath);
            userService.saveOrUpdate(user);
            if(file.exists()){
                file.delete();
            }
            return Result.succ("上传成功！",user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail("上传失败");
    }


    /*
     * 实时个人头像
     * */

    @RequestMapping("/getPic")
    public Result getPic(@RequestParam("id") Integer id){
        User user = userService.getById(id);
        return Result.succ(user);
    }

    /*
     *实时拿到余额
     * */

    @RequestMapping("/getBalance")
    public Result getBalance(@RequestParam("id") Integer id){
        User user = userService.getById(id);
        System.out.println(user);
        return Result.succ(user.getBalance());
    }

    /*
     *充值余额
     * */

    @RequestMapping("/recharge")
    public Result recharge(@RequestParam("id") Integer id){
        User user = userService.getById(id);
        System.out.println("余额是：  "+user.getBalance());
        String balance =  user.getBalance();
        user.setBalance(String.valueOf(Double.valueOf(balance)+100));
        userService.saveOrUpdate(user);
        return Result.succ("充值成功");
    }
    /*
    * 充值
    * */

    @RequestMapping("/recharges")
    public Result buy(@RequestParam("id") Integer id,
                      @RequestParam("balance") Double balance){
        User user = userService.getById(id);
        user.setBalance(String.valueOf(Double.valueOf(user.getBalance())+balance));
        userService.saveOrUpdate(user);

        Date date = new Date();

        //随机生成订单号uuid
        String str = UUID.randomUUID().toString().replaceAll("-", "");
        Rechargerecord rechargerecord = new Rechargerecord();
        rechargerecord.setId(str);
        rechargerecord.setUserId(id);
        rechargerecord.setCreated(date);
        rechargerecord.setBalance(String.valueOf(balance));
        rechargerecordService.saveOrUpdate(rechargerecord);
        return Result.succ("充值正常");
    }

    /*
    * 拿到所有用户信息
    * */

    @RequestMapping("/user/getalls")
    public Result getalls(){
        List<User> users = userService.list();
        HashMap<String, List<User>> map = new HashMap<>();
        map.put("userlist",users);
        return Result.succ(map);
    }

    /*
    * 根据分页获取所有用户
    * */

    @RequestMapping("/user/getall")
    public Result getall(Integer currentPage){

        if(currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        Page<User> page = new Page<>(currentPage,5);
        IPage<User> page1 = userService.page(page, new QueryWrapper<User>());

        return Result.succ(page1);
    }

    /*
    * 搜索
    * */

    @GetMapping("/search")
    public Result search(Integer currentPage,String search){

        if(currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        Page<User> page = new Page<>(currentPage,5);
        IPage<User> page1 = userService.page(page, new QueryWrapper<User>().like("username","%"+search+"%"));
        return  Result.succ(page1);
    }

    /*
    * 根据id删除用户
    * */

    @GetMapping("/deleteById")
    public Result deletebyid(String id){
        userService.removeById(Integer.parseInt(id));
        return Result.succ("删除成功");
    }
}
